<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>校区管理员 - 乒乓球培训管理系统</title>
  <link rel="stylesheet" href="../assets/css/common.css">
  <style>
    .quick-actions {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;
      margin-bottom: 30px;
    }

    .quick-action {
      background: white;
      border: 2px solid var(--border-color);
      border-radius: 8px;
      padding: 20px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;
    }

    .quick-action:hover {
      border-color: var(--primary-color);
      transform: translateY(-2px);
      box-shadow: var(--shadow);
    }

    .quick-action-icon {
      font-size: 32px;
      margin-bottom: 12px;
    }

    .quick-action-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .quick-action-desc {
      font-size: 12px;
      color: var(--text-muted);
    }

    .pending-badge {
      background: var(--error-color);
      color: white;
      font-size: 12px;
      padding: 2px 6px;
      border-radius: 10px;
      position: absolute;
      top: -8px;
      right: -8px;
    }

    .coach-card {
      border: 1px solid var(--border-color);
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;
      background: white;
    }

    .coach-header {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 12px;
    }

    .coach-avatar {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      background: var(--bg-light);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
    }

    .coach-info h4 {
      margin: 0 0 4px 0;
      font-size: 18px;
    }

    .coach-info p {
      margin: 0;
      color: var(--text-muted);
      font-size: 14px;
    }

    .coach-actions {
      display: flex;
      gap: 8px;
    }

    .coach-details {
      background: var(--bg-light);
      padding: 12px;
      border-radius: 6px;
      margin-bottom: 12px;
    }

    .coach-details p {
      margin: 4px 0;
      font-size: 14px;
    }

    .level-selector {
      display: flex;
      gap: 8px;
      margin-bottom: 12px;
    }

    .level-btn {
      padding: 6px 12px;
      border: 1px solid var(--border-color);
      background: white;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
    }

    .level-btn.selected {
      background: var(--primary-color);
      color: white;
      border-color: var(--primary-color);
    }

    .recharge-form {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;
      align-items: end;
    }

    .competition-schedule {
      background: white;
      border: 1px solid var(--border-color);
      border-radius: 8px;
      overflow: hidden;
    }

    .schedule-header {
      background: var(--primary-color);
      color: white;
      padding: 12px 16px;
      font-weight: 600;
    }

    .schedule-content {
      padding: 16px;
    }

    .match-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid var(--border-color);
    }

    .match-item:last-child {
      border-bottom: none;
    }

    .match-players {
      font-weight: 500;
    }

    .match-info {
      font-size: 12px;
      color: var(--text-muted);
    }

    .calendar {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 1px;
      background: var(--border-color);
      border: 1px solid var(--border-color);
      border-radius: 6px;
      overflow: hidden;
    }

    .calendar-header {
      background: var(--primary-color);
      color: white;
      padding: 8px;
      text-align: center;
      font-weight: 600;
      font-size: 12px;
    }

    .calendar-day {
      background: white;
      padding: 8px;
      min-height: 60px;
      font-size: 12px;
      position: relative;
    }

    .calendar-day.other-month {
      background: var(--bg-light);
      color: var(--text-muted);
    }

    .calendar-day.today {
      background: #fff5e6;
      color: var(--primary-color);
      font-weight: 600;
    }

    .booking-dot {
      width: 6px;
      height: 6px;
      background: var(--primary-color);
      border-radius: 50%;
      position: absolute;
      bottom: 4px;
      right: 4px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="page-header">
      <h1 class="page-title">校区管理员控制台</h1>
      <div>
        <span class="text-muted">中心校区 - 张主任</span>
        <button class="btn btn-secondary btn-sm" onclick="logout()" style="margin-left: 12px;">退出登录</button>
      </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <div class="quick-action" onclick="switchTab('coach')" style="position: relative;">
        <div class="quick-action-icon">👨‍🏫</div>
        <div class="quick-action-title">教练审核</div>
        <div class="quick-action-desc">待审核教练申请</div>
        <span class="pending-badge">3</span>
      </div>
      <div class="quick-action" onclick="switchTab('student')">
        <div class="quick-action-icon">👨‍🎓</div>
        <div class="quick-action-title">学员管理</div>
        <div class="quick-action-desc">学员信息维护</div>
      </div>
      <div class="quick-action" onclick="switchTab('booking')">
        <div class="quick-action-icon">📅</div>
        <div class="quick-action-title">预约管理</div>
        <div class="quick-action-desc">课程预约排课</div>
      </div>
      <div class="quick-action" onclick="switchTab('competition')">
        <div class="quick-action-icon">🏆</div>
        <div class="quick-action-title">月赛管理</div>
        <div class="quick-action-desc">比赛组织安排</div>
      </div>
      <div class="quick-action" onclick="switchTab('finance')">
        <div class="quick-action-icon">💰</div>
        <div class="quick-action-title">财务管理</div>
        <div class="quick-action-desc">充值退款记录</div>
      </div>
      <div class="quick-action" onclick="switchTab('message')">
        <div class="quick-action-icon">📢</div>
        <div class="quick-action-title">消息通知</div>
        <div class="quick-action-desc">系统消息日志</div>
      </div>
    </div>

    <!-- 功能标签页 -->
    <div class="tab-container">
      <div class="tab-header">
        <button class="tab-btn active" onclick="switchTab('coach')">教练审核</button>
        <button class="tab-btn" onclick="switchTab('student')">学员管理</button>
        <button class="tab-btn" onclick="switchTab('booking')">预约管理</button>
        <button class="tab-btn" onclick="switchTab('competition')">月赛管理</button>
        <button class="tab-btn" onclick="switchTab('finance')">财务管理</button>
        <button class="tab-btn" onclick="switchTab('message')">消息日志</button>
      </div>

      <!-- 教练审核 -->
      <div id="coachTab" class="tab-content tab-pane active">
        <h3>教练审核</h3>
        <div id="pendingCoaches"></div>
      </div>

      <!-- 学员管理 -->
      <div id="studentTab" class="tab-content tab-pane">
        <div class="action-bar">
          <h3>学员管理</h3>
          <div class="search-box">
            <input type="text" class="form-control" placeholder="搜索学员..." id="studentSearch">
            <button class="btn btn-primary" onclick="showRechargeModal()">学员充值</button>
          </div>
        </div>
        <div id="studentTable"></div>
      </div>

      <!-- 预约管理 -->
      <div id="bookingTab" class="tab-content tab-pane">
        <h3>预约管理</h3>
        <div class="row">
          <div class="col-8">
            <div class="card">
              <div class="card-header">预约日历</div>
              <div class="card-body">
                <div id="bookingCalendar"></div>
              </div>
            </div>
          </div>
          <div class="col-4">
            <div class="card">
              <div class="card-header">今日预约</div>
              <div class="card-body">
                <div id="todayBookings"></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 月赛管理 -->
      <div id="competitionTab" class="tab-content tab-pane">
        <div class="action-bar">
          <h3>月赛管理</h3>
          <button class="btn btn-primary" onclick="generateSchedule()">生成赛程</button>
        </div>
        <div class="row">
          <div class="col-4">
            <div class="card">
              <div class="card-header">报名统计</div>
              <div class="card-body">
                <div id="enrollmentStats"></div>
              </div>
            </div>
          </div>
          <div class="col-8">
            <div class="competition-schedule">
              <div class="schedule-header">甲组赛程</div>
              <div class="schedule-content" id="groupASchedule"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 财务管理 -->
      <div id="financeTab" class="tab-content tab-pane">
        <h3>财务管理</h3>
        <div id="financeTable"></div>
      </div>

      <!-- 消息日志 -->
      <div id="messageTab" class="tab-content tab-pane">
        <div class="action-bar">
          <h3>消息日志</h3>
          <button class="btn btn-primary" onclick="showBroadcastModal()">群发消息</button>
        </div>
        <div id="messageTable"></div>
      </div>
    </div>
  </div>

  <!-- 学员充值模态框 -->
  <div id="rechargeModal" class="modal-overlay" style="display: none;">
    <div class="modal">
      <div class="modal-header">
        <h3 class="modal-title">学员充值</h3>
        <button class="modal-close" onclick="hideRechargeModal()">&times;</button>
      </div>
      <div class="modal-body">
        <form id="rechargeForm" onsubmit="handleRecharge(event)">
          <div class="recharge-form">
            <div class="form-group">
              <label class="form-label">学员姓名</label>
              <select class="form-control form-select" name="studentId" required>
                <option value="">请选择学员</option>
                <option value="1">张小明</option>
                <option value="2">李小红</option>
                <option value="3">王小刚</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">充值金额</label>
              <input type="number" class="form-control" name="amount" placeholder="请输入金额" min="1" step="0.01" required>
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">备注</label>
            <textarea class="form-control" name="note" rows="2" placeholder="充值备注（可选）"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" onclick="hideRechargeModal()">取消</button>
        <button class="btn btn-primary" onclick="document.getElementById('rechargeForm').requestSubmit()">确认充值</button>
      </div>
    </div>
  </div>

  <script src="../assets/js/common.js"></script>
  <script>
    // 模拟数据
    const pendingCoaches = [
      {
        id: '1',
        name: '李教练',
        gender: '男',
        age: 28,
        phone: '138-0000-0101',
        email: 'coach1@example.com',
        achievements: '2022年市级比赛第二名，2023年省级比赛第五名，有5年教学经验',
        appliedAt: '2024-01-14 10:30:00'
      },
      {
        id: '2',
        name: '王教练',
        gender: '女',
        age: 25,
        phone: '138-0000-0102',
        email: 'coach2@example.com',
        achievements: '国家二级运动员，曾获全国青少年比赛冠军',
        appliedAt: '2024-01-13 15:20:00'
      }
    ];

    const students = MockData.generateUsers(15, 'student').map(user => ({
      ...user,
      balance: (Math.random() * 1000).toFixed(2),
      coachCount: Math.floor(Math.random() * 3),
      lastLogin: Utils.formatDate(new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000))
    }));

    const todayBookings = [
      { time: '09:00-10:00', student: '张小明', coach: '李教练', table: '球台1' },
      { time: '10:00-11:00', student: '李小红', coach: '王教练', table: '球台2' },
      { time: '14:00-15:00', student: '王小刚', coach: '李教练', table: '球台1' },
      { time: '15:00-16:00', student: '赵小丽', coach: '张教练', table: '球台3' }
    ];

    const enrollmentStats = {
      groupA: 8,
      groupB: 12,
      groupC: 15
    };

    const groupAMatches = [
      { round: 1, player1: '张小明', player2: '李小红', table: '球台1', time: '09:00' },
      { round: 1, player3: '王小刚', player4: '赵小丽', table: '球台2', time: '09:00' },
      { round: 2, player1: '张小明', player2: '王小刚', table: '球台1', time: '10:00' },
      { round: 2, player3: '李小红', player4: '赵小丽', table: '球台2', time: '10:00' }
    ];

    function switchTab(tabName) {
      // 切换标签按钮状态
      document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
      document.querySelector(`.tab-btn[onclick="switchTab('${tabName}')"]`).classList.add('active');

      // 切换内容面板
      document.querySelectorAll('.tab-pane').forEach(pane => pane.classList.remove('active'));
      document.getElementById(tabName + 'Tab').classList.add('active');

      // 加载对应数据
      switch(tabName) {
        case 'coach':
          loadPendingCoaches();
          break;
        case 'student':
          loadStudentTable();
          break;
        case 'booking':
          loadBookingCalendar();
          loadTodayBookings();
          break;
        case 'competition':
          loadCompetitionData();
          break;
        case 'finance':
          loadFinanceTable();
          break;
        case 'message':
          loadMessageTable();
          break;
      }
    }

    function loadPendingCoaches() {
      const container = document.getElementById('pendingCoaches');
      const html = pendingCoaches.map(coach => `
        <div class="coach-card">
          <div class="coach-header">
            <div class="coach-avatar">👨‍🏫</div>
            <div class="coach-info">
              <h4>${coach.name}</h4>
              <p>${coach.gender} · ${coach.age}岁 · ${coach.phone}</p>
              <p>申请时间：${coach.appliedAt}</p>
            </div>
          </div>
          <div class="coach-details">
            <p><strong>邮箱：</strong>${coach.email}</p>
            <p><strong>比赛成绩：</strong>${coach.achievements}</p>
          </div>
          <div class="form-group">
            <label class="form-label">选择教练等级：</label>
            <div class="level-selector">
              <button class="level-btn" data-level="junior" onclick="selectLevel(this, 'junior')">初级教练 (80元/时)</button>
              <button class="level-btn selected" data-level="middle" onclick="selectLevel(this, 'middle')">中级教练 (150元/时)</button>
              <button class="level-btn" data-level="senior" onclick="selectLevel(this, 'senior')">高级教练 (200元/时)</button>
            </div>
          </div>
          <div class="coach-actions">
            <button class="btn btn-success" onclick="approveCoach('${coach.id}', this.closest('.coach-card'))">通过</button>
            <button class="btn btn-danger" onclick="rejectCoach('${coach.id}', this.closest('.coach-card'))">拒绝</button>
          </div>
        </div>
      `).join('');
      
      container.innerHTML = html || '<p class="text-muted">暂无待审核的教练申请</p>';
    }

    function selectLevel(btn, level) {
      btn.closest('.level-selector').querySelectorAll('.level-btn').forEach(b => b.classList.remove('selected'));
      btn.classList.add('selected');
    }

    function approveCoach(id, cardEl) {
      const selectedLevel = cardEl.querySelector('.level-btn.selected').dataset.level;
      const levelText = {
        'junior': '初级教练',
        'middle': '中级教练',
        'senior': '高级教练'
      }[selectedLevel];
      
      Utils.confirm(`确定将该教练审核为${levelText}吗？`, () => {
        cardEl.remove();
        Utils.showMessage(`教练审核通过，等级：${levelText}`, 'success');
      });
    }

    function rejectCoach(id, cardEl) {
      Utils.confirm('确定要拒绝该教练申请吗？', () => {
        cardEl.remove();
        Utils.showMessage('已拒绝教练申请', 'warning');
      });
    }

    function loadStudentTable() {
      const columns = [
        { key: 'realName', title: '姓名' },
        { key: 'gender', title: '性别' },
        { key: 'age', title: '年龄' },
        { key: 'phone', title: '手机号' },
        { 
          key: 'balance', 
          title: '账户余额',
          render: (value) => `<span class="text-success">¥${value}</span>`
        },
        { key: 'coachCount', title: '教练数' },
        { key: 'lastLogin', title: '最后登录' },
        { 
          key: 'status', 
          title: '状态',
          render: (value) => `<span class="status-badge status-success">${value}</span>`
        }
      ];

      const actions = [
        { text: '查看详情', class: 'btn-secondary', onclick: 'viewStudent' },
        { text: '充值', class: 'btn-primary', onclick: 'rechargeStudent' },
        { text: '禁用', class: 'btn-danger', onclick: 'disableStudent' }
      ];

      Table.render('studentTable', columns, students, { actions });
    }

    function loadBookingCalendar() {
      const calendar = document.getElementById('bookingCalendar');
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth();
      
      // 生成日历
      const firstDay = new Date(year, month, 1);
      const lastDay = new Date(year, month + 1, 0);
      const daysInMonth = lastDay.getDate();
      const startingDay = firstDay.getDay();
      
      let html = '';
      
      // 星期标题
      const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
      weekdays.forEach(day => {
        html += `<div class="calendar-header">${day}</div>`;
      });
      
      // 空白日期
      for (let i = 0; i < startingDay; i++) {
        html += `<div class="calendar-day other-month"></div>`;
      }
      
      // 月份日期
      for (let day = 1; day <= daysInMonth; day++) {
        const isToday = day === today.getDate();
        const hasBooking = Math.random() > 0.7; // 随机生成预约
        html += `
          <div class="calendar-day ${isToday ? 'today' : ''}">
            ${day}
            ${hasBooking ? '<div class="booking-dot"></div>' : ''}
          </div>
        `;
      }
      
      calendar.innerHTML = html;
    }

    function loadTodayBookings() {
      const container = document.getElementById('todayBookings');
      const html = todayBookings.map(booking => `
        <div style="padding: 8px 0; border-bottom: 1px solid #eee;">
          <div style="font-weight: 500;">${booking.time}</div>
          <div style="font-size: 12px; color: #666;">
            ${booking.student} · ${booking.coach} · ${booking.table}
          </div>
        </div>
      `).join('');
      
      container.innerHTML = html;
    }

    function loadCompetitionData() {
      // 报名统计
      const statsHtml = `
        <div style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #eee;">
          <span>甲组</span>
          <span class="text-primary">${enrollmentStats.groupA}人</span>
        </div>
        <div style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #eee;">
          <span>乙组</span>
          <span class="text-primary">${enrollmentStats.groupB}人</span>
        </div>
        <div style="display: flex; justify-content: space-between; padding: 8px 0;">
          <span>丙组</span>
          <span class="text-primary">${enrollmentStats.groupC}人</span>
        </div>
      `;
      document.getElementById('enrollmentStats').innerHTML = statsHtml;
      
      // 甲组赛程
      const scheduleHtml = groupAMatches.map(match => `
        <div class="match-item">
          <div class="match-players">${match.player1} vs ${match.player2}</div>
          <div class="match-info">${match.table} · ${match.time}</div>
        </div>
      `).join('');
      document.getElementById('groupASchedule').innerHTML = scheduleHtml;
    }

    function loadFinanceTable() {
      const financeData = [
        { id: '1', type: '充值', student: '张小明', amount: '+200.00', method: '线下', time: '2024-01-15 10:30:00' },
        { id: '2', type: '消费', student: '李小红', amount: '-150.00', method: '预约扣费', time: '2024-01-15 09:00:00' },
        { id: '3', type: '退款', student: '王小刚', amount: '+80.00', method: '取消预约', time: '2024-01-14 16:20:00' }
      ];

      const columns = [
        { key: 'type', title: '类型' },
        { key: 'student', title: '学员' },
        { 
          key: 'amount', 
          title: '金额',
          render: (value) => {
            const isPositive = value.startsWith('+');
            return `<span class="text-${isPositive ? 'success' : 'danger'}">¥${value}</span>`;
          }
        },
        { key: 'method', title: '方式' },
        { key: 'time', title: '时间' }
      ];

      Table.render('financeTable', columns, financeData);
    }

    function loadMessageTable() {
      const messageData = [
        { id: '1', type: '系统消息', title: '教练审核通知', content: '李教练的申请已审核通过', time: '2024-01-15 14:30:00' },
        { id: '2', type: '预约提醒', title: '课程提醒', content: '张小明的课程将在1小时后开始', time: '2024-01-15 14:00:00' },
        { id: '3', type: '月赛通知', title: '月赛报名开始', content: '1月月赛报名已开放，截止时间：1月25日', time: '2024-01-15 09:00:00' }
      ];

      const columns = [
        { key: 'type', title: '类型' },
        { key: 'title', title: '标题' },
        { key: 'content', title: '内容' },
        { key: 'time', title: '时间' }
      ];

      const actions = [
        { text: '查看', class: 'btn-secondary', onclick: 'viewMessage' },
        { text: '删除', class: 'btn-danger', onclick: 'deleteMessage' }
      ];

      Table.render('messageTable', columns, messageData, { actions });
    }

    function showRechargeModal() {
      document.getElementById('rechargeModal').style.display = 'flex';
    }

    function hideRechargeModal() {
      document.getElementById('rechargeModal').style.display = 'none';
      document.getElementById('rechargeForm').reset();
    }

    function handleRecharge(event) {
      event.preventDefault();
      const formData = new FormData(event.target);
      const amount = formData.get('amount');
      
      Utils.showMessage(`充值成功！金额：¥${amount}`, 'success');
      hideRechargeModal();
      loadStudentTable();
    }

    function generateSchedule() {
      Utils.showMessage('赛程生成成功！', 'success');
      loadCompetitionData();
    }

    function showBroadcastModal() {
      const modalId = Modal.create('群发消息', `
        <form id="broadcastForm">
          <div class="form-group">
            <label class="form-label">接收对象</label>
            <select class="form-control form-select" name="target" required>
              <option value="">请选择</option>
              <option value="all">全体用户</option>
              <option value="students">所有学员</option>
              <option value="coaches">所有教练</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">消息标题</label>
            <input type="text" class="form-control" name="title" required>
          </div>
          <div class="form-group">
            <label class="form-label">消息内容</label>
            <textarea class="form-control" name="content" rows="4" required></textarea>
          </div>
        </form>
      `, [
        { text: '取消', class: 'btn-secondary' },
        { text: '发送', class: 'btn-primary', onclick: 'sendBroadcast()' }
      ]);
      Modal.show(modalId);
    }

    function sendBroadcast() {
      Utils.showMessage('消息发送成功！', 'success');
      Modal.hide(document.querySelector('.modal-overlay').id);
    }

    function viewStudent(id) { Utils.showMessage('查看学员详情...', 'info'); }
    function rechargeStudent(id) { showRechargeModal(); }
    function disableStudent(id) { Utils.showMessage('学员已禁用', 'warning'); }
    function viewMessage(id) { Utils.showMessage('查看消息详情...', 'info'); }
    function deleteMessage(id) { Utils.showMessage('消息已删除', 'success'); }

    function logout() {
      Utils.confirm('确定要退出登录吗？', () => {
        if (window.parent && window.parent.switchPage) {
          window.parent.switchPage('auth.html', 'login');
        } else {
          window.location.href = 'auth.html';
        }
      });
    }

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
      loadPendingCoaches();
    });
  </script>
</body>
</html>
